package com.shr25.test;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

public class JasyptUtils {

  /**
   * 配置文件中设定的加密密码 jasypt.encryptor.password
   */
  private static String password = "shr25";

  public static void init(String password) {
    JasyptUtils.password = password;
  }

  /**
   * Jasypt生成加密结果
   *
   * @param value 待加密值
   * @return
   */
  public static String encryptPwd(String value) {
    PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
    encryptOr.setConfig(cryptOr());
    String result = encryptOr.encrypt(value);
    return result;
  }

  /**
   * 解密
   *
   * @param value 待解密密文
   * @return
   */
  public static String decyptPwd(String value) {
    PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
    encryptOr.setConfig(cryptOr());
    String result = encryptOr.decrypt(value);
    return result;
  }

  /**
   * @return
   */
  public static SimpleStringPBEConfig cryptOr() {
    if (password == null) {
      throw new RuntimeException("没有初始化盐");
    }
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();
    config.setPassword(password);
    config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
    config.setKeyObtentionIterations("1000");
    config.setPoolSize("1");
    config.setProviderName(null);
    config.setProviderClassName(null);
    config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
    config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
    config.setStringOutputType("base64");
    return config;
  }

  public static void main(String[] args) {

  }
}
